# ------------------------------------------------------------------------------
# Motion Detection Detector
# ------------------------------------------------------------------------------
# 检测画面中的运动
# ------------------------------------------------------------------------------

import cv2
import numpy as np
from .base_detector import BaseDetector


class MotionDetector(BaseDetector):
    """运动检测器"""
    
    def __init__(self, threshold=100):
        super().__init__()
        self.threshold = threshold
        self.previous_frame = None
        self.motion_detected = False
        
    def mse(self, image_a, image_b):
        """计算均方误差"""
        err = np.sum((image_a.astype("float") - image_b.astype("float")) ** 2)
        err /= float(image_a.shape[0] * image_a.shape[1])
        return err
        
    def process_frame(self, frame):
        """
        检测运动并在图像上显示
        
        Args:
            frame: 输入图像帧
            
        Returns:
            display_frame: 显示帧（包含边缘检测和运动状态）
        """
        self.update_fps()
        
        # 应用高斯模糊去噪
        blurred = cv2.GaussianBlur(frame, (3, 3), 0)
        
        # 转换为灰度图
        gray = cv2.cvtColor(blurred, cv2.COLOR_BGR2GRAY)
        
        # 检测边缘
        edges = cv2.Canny(gray, 100, 200)
        
        # 检测运动
        self.motion_detected = False
        if self.previous_frame is not None:
            mse_value = self.mse(gray, self.previous_frame)
            if mse_value > self.threshold:
                self.motion_detected = True
        
        # 保存当前帧用于下次比较
        self.previous_frame = gray.copy()
        
        # 创建显示帧（原图 + 边缘检测）
        edges_colored = cv2.cvtColor(edges, cv2.COLOR_GRAY2BGR)
        display_frame = cv2.hconcat([frame, edges_colored])
        
        # 显示运动检测状态
        if self.motion_detected:
            status_text = '状态: 检测到运动!'
            status_color = (0, 0, 255)  # 红色
        else:
            status_text = '状态: 无运动'
            status_color = (0, 255, 0)  # 绿色
            
        cv2.putText(display_frame, status_text, (24, 50), 
                   cv2.FONT_HERSHEY_PLAIN, 1.2, status_color, 2)
        
        display_frame = self.visualize_fps(display_frame)
        return display_frame

